package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.OrderDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功！");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(name != null, Dish::getName, name);
        //排序
        lqw.orderByAsc(Dish::getPrice).orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(dishPage, lqw);

        //对象拷贝，将dishPage的内容拷贝到dishDtoPage
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据id获取分类对象
            Category category = categoryService.getById(categoryId);
            //获取分类名
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dishCache", key = "'dish' + '_' + #id", unless = "#result == null")
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 根据id修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);


        return R.success("菜品修改成功！");
    }

    /**
     * 删除菜品信息和口味信息
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {

        log.info("ids为：{}", ids);
        dishService.deleteWithFlavor(ids);
        return R.success("菜品删除成功！");
    }

    /**
     * 停售和起售
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        log.info("status:{},ids:{}", status, ids);

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Dish::getId, ids);
        lqw.eq(status != null, Dish::getStatus, status);

        int count = dishService.count(lqw);

        if (count > 0) {
            throw new CustomException("请勿重复操作");
        }

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);


        Dish dish = new Dish();
        dish.setStatus(status);

        dishService.update(dish, qw);

        return R.success("菜品状态已更改成功");
    }


    /**
     * 根据条件查询菜品信息
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "dishCache", key = "#dish.categoryId + '_' + #dish.name", unless = "#result == null")
    @GetMapping("/list")
    public R<List<DishDto>> getList(Dish dish) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        // 添加条件，分类id
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 添加条件，菜名
        lqw.like(dish.getName() != null, Dish::getName, dish.getName());
        // 添加条件，查询状态未1(起售状态)的菜品
        lqw.eq(Dish::getStatus, 1);
        // 添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        List<DishDto> dishDtos = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            // 根据id查询分类对象
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            // 根据当前菜品id查询口味信息
            LambdaQueryWrapper<DishFlavor> dlqw = new LambdaQueryWrapper<>();
            dlqw.eq(DishFlavor::getDishId, item.getId());
            dishDto.setFlavors(dishFlavorService.list(dlqw));

            // 查询月销量
            Integer saleNum = dishService.countSaleNum(item.getId(), null, null);
            dishDto.setSaleNum(saleNum);

            return dishDto;
        }).collect(Collectors.toList());

        // 如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis中
        // redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }


    /**
     * 菜品推荐
     *
     * @return null
     */
    @Cacheable(value = "orderCache", key = "'getRecommend'", unless = "#result == null")
    @GetMapping("/recommend")
    public R<List<DishDto>> getRecommend() {
        //有序存储菜品图片和菜品id到hashset集合中
        //添加排序构造器
        //查询所有菜品信息
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        LinkedList<Long> longs = new LinkedList<>();
        longs.add(1413384954989060097L);
        longs.add(1413341197421846529L);
        queryWrapper.notIn(Dish::getCategoryId, longs);
        List<Dish> dishList = dishService.list(queryWrapper);
        List<DishDto> ts = new ArrayList<>(dishList.size());
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //通过菜品信息 查询菜品销量
            Integer dishCount = dishService.countSaleNum(dish.getId(), null, null);
            dishDto.setSaleNum(dishCount);
            BeanUtils.copyProperties(dish, dishDto);
            //将菜品添加到集合中
            ts.add(dishDto);
        }
        ts.sort(new Comparator<DishDto>() {
            @Override
            public int compare(DishDto o1, DishDto o2) {
                //降序排列
                return o2.getSaleNum() - o1.getSaleNum();
            }
        });
        ArrayList<DishDto> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(ts.get(i));
        }
        for (int i = 0; i < list.size(); i++) {
            // 根据id查询分类对象
            Category category = categoryService.getById(list.get(i).getCategoryId());
            if (category != null) {
                list.get(i).setCategoryName(category.getName());
            }
            // 根据当前菜品id查询口味信息
            LambdaQueryWrapper<DishFlavor> dlqw = new LambdaQueryWrapper<>();
            dlqw.eq(DishFlavor::getDishId, list.get(i).getId());
            list.get(i).setFlavors(dishFlavorService.list(dlqw));
        }
        return R.success(list);
    }

}


